using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using AXBC = Microsoft.Dynamics.BusinessConnectorNet;
using AXMD = Microsoft.Dynamics.Framework.Metadata.Ax;
using Proxy = Microsoft.Dynamics.Framework.BusinessConnector.Proxy;

namespace DynamicsAXPS
{
    [System.Management.Automation.Cmdlet("Get", "AXNodeProperties")]
    public class Get_AXNodeProperties : System.Management.Automation.PSCmdlet
    {
        [System.Management.Automation.Parameter(Position = 0, Mandatory = true)]
        public string Path = "\\";

        protected override void ProcessRecord()
        {
            var ax_session = Microsoft.Dynamics.Framework.Portal.SessionHelper.Instance.GetSession();
            var node = Proxy.TreeNode.findNode(ax_session.AxaptaAdapter, Path);
            var props = node.AOTgetProperties().Trim();
            var lines = props.Split(new[] { '\n' });
            var actual_lines = lines.Skip(1).Take(lines.Count() - 2).ToList();

            var dic = new Dictionary<string, string>(actual_lines.Count);
            foreach (var line in actual_lines)
            {
                int n = line.IndexOf('#');
                if (n < 1)
                {
                    throw new Exception(line);
                }

                string name = line.Substring(0, n - 1).Trim();
                string value = line.Substring(n + 1).Trim();
                dic[name] = value;
            }
            this.WriteObject(dic);
        }
    }
}
